package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQueryObject;
import cn.wolfcode.wolf2w.repository.RegionMongoRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMongoRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        repository.save(region);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public void update(Region region) {
        repository.save(region);
    }

    @Override
    public Region find(String id) {
        Region region = repository.findById(id).orElse(null);

        return region;
    }

    @Override
    public List<Region> findAll() {
        List<Region> list = repository.findAll();
        return list;
    }

    @Override
    public Page list(RegionQueryObject qo) {
        //查询对象
        Query query = new Query();
        //查询总条数
        long count = template.count(query, Region.class);
        if(count == 0){
            //没有记录返回空页面
            return Page.empty();
        }
        //分页对象
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "sequence");
        query.with(pageable);
        List<Region> list = template.find(query, Region.class);
        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void changeHotValue(String id, int hot) {
        //部分字段更新
        //db.集合.update({_id:id},{$set:{ishot:hot}})
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        //创建更新对象
        Update update = new Update();
        update.set("ishot",hot);
        template.updateMulti(query,update,Region.class);
    }

    @Override
    public List<Region> queryHotRegion() {
        Query query = new Query();
        query.with(Sort.by(Sort.Direction.ASC,"sequence"));
        List<Region> list = template.find(query, Region.class);
        return list;
    }
}
